﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;
using System.Data.SqlClient;

namespace 提交管理平台V1
{
    public partial class ProductDocPrintFrm : Form
    {
        DataGridViewSelectedRowCollection dgvsrc;
        DataSet ds;
        string strReportFileName;
        string strInsertDPAID = "INSERT INTO [DefualtDataBase].[dbo].[DPA报告编号表]([DPA报告编号], [批号], [型号规格], [打印时间]) VALUES('@DPA报告编号','@批号','@型号规格',getdate())";

        public ProductDocPrintFrm(DataGridViewSelectedRowCollection tmpdgvsrc)
        {
            InitializeComponent();
            dgvsrc = tmpdgvsrc;
        }

        private void ProductDocPrintFrm_Load(object sender, EventArgs e)
        {
            cmbDocType.SelectedIndex = 0;
        }

        private void cmbDocType_SelectedIndexChanged(object sender, EventArgs e)
        {
            ds = iniDataset(cmbDocType.SelectedIndex);
            dgv1.DataSource = ds.Tables [0];
            dgv1.AutoResizeColumns();
        }

        private DataSet iniDataset(int iDocType)
        {
            DataSet tmpds = new DataSet();
            DataTable tmpdt = new DataTable();
            DataRow r;
            switch (iDocType)
            {
                case 0:
                    dgv1.ContextMenuStrip = contextMenuStrip1;
                    if (!CheckDataFieldExist("型号;尺寸;特性;电压;容量;技术条件;生产日期;批号"))
                    {
                        return null;
                    }
                    tmpdt.TableName = "ReportData";
                    tmpdt.Columns.Add("型号规格");
                    tmpdt.Columns.Add("生产日期");
                    tmpdt.Columns.Add("生产批号");
                    tmpdt.Columns.Add("规定抽样数");
                    tmpdt.Columns.Add("引出端强度");
                    tmpdt.Columns.Add("内部目检");
                    tmpdt.Columns.Add("DPA报告编号");
                    string strReportMonth = DateTime.Now.ToString("yyyy-MM");
                    string strLastReportMonth = Properties.Settings.Default.DPA报告编号.Substring(0, 7);
                    int iReportID;
                    if (strReportMonth != strLastReportMonth)
                    {
                        iReportID = 0;
                    }
                    else
                    {
                        iReportID =Convert .ToInt32 (Properties.Settings.Default.DPA报告编号.Substring(8, 4));
                    }
                    for (int i = 0; i < dgvsrc.Count; i++)
                    {
                        r = tmpdt.NewRow();
                        string strClass = string.Empty;
                        if (GetString(dgvsrc[i].Cells["技术条件"].Value).Contains("CAST"))
                        {
                            strClass = "CC";
                        }
                        if (GetString(dgvsrc[i].Cells["技术条件"].Value).Contains("LMS"))
                        {
                            strClass = "G+";
                        }
                        if (GetString(dgvsrc[i].Cells["技术条件"].Value).Trim ()=="G")
                        {
                            strClass = "G";
                        }
                        if (strClass == string.Empty)
                        {
                            r["型号规格"] = GetString(dgvsrc[i].Cells["型号"].Value) + "-" +
                                GetString(dgvsrc[i].Cells["尺寸"].Value) + "-" +
                                GetString(dgvsrc[i].Cells["特性"].Value) + "-" +
                                GetString(dgvsrc[i].Cells["电压"].Value) + "-" +
                                GetString(dgvsrc[i].Cells["容量"].Value);
                        }
                        else
                        {
                            r["型号规格"] = "(" + strClass + ") " + (dgvsrc[i].Cells["型号"].Value) + "-" +
                                GetString(dgvsrc[i].Cells["尺寸"].Value) + "-" +
                                GetString(dgvsrc[i].Cells["特性"].Value) + "-" +
                                GetString(dgvsrc[i].Cells["电压"].Value) + "-" +
                                GetString(dgvsrc[i].Cells["容量"].Value);
                        }
                        r["生产日期"] = GetString(dgvsrc[i].Cells["生产日期"].Value).Substring (0,GetString(dgvsrc[i].Cells["生产日期"].Value).IndexOf (' '));
                        r["生产批号"] = GetString(dgvsrc[i].Cells["批号"].Value);
                        if (GetString(dgvsrc[i].Cells["型号"].Value).Trim ().Contains ("41"))
                        {
                            r["引出端强度"] = "/";
                            r["内部目检"] = "/";
                            if (GetString(dgvsrc[i].Cells["尺寸"].Value).Trim().CompareTo ( "1812")<0)
                            {
                                r["规定抽样数"] = 10;
                            }
                            else
                            {
                                r["规定抽样数"] = 5;
                            }
                        }
                        else 
                        {
                            r["引出端强度"] = "合格";
                            r["内部目检"] = "合格";
                            r["规定抽样数"] = 5;
                        }
                        iReportID++;
                        r["DPA报告编号"] = strReportMonth + "-" + iReportID.ToString("0000");
                        tmpdt.Rows.Add(r);
                    }
                    tmpds.Tables.Add(tmpdt);
                    return tmpds;
                    break;
                default :
                    dgv1.ContextMenuStrip = null;
                    return null;
                    break;
            }
        }

        private bool CheckDataFieldExist(string strFieldToCheck)
        {
            string[] strFields = strFieldToCheck.Split(';');
            if (strFields.Length > 0&&dgvsrc .Count >0)
            {
                for (int i = 0; i < strFields.Length; i++)
                {
                    bool bResult = false;
                    if (strFields[i].Trim().Length == 0)
                    {
                        continue;
                    }
                    else
                    {
                        for (int j = 0; j < dgvsrc[0].DataGridView.Columns.Count; j++)
                        {
                            if (strFields[i].Trim() == dgvsrc[0].DataGridView.Columns[j].Name.Trim())
                            {
                                bResult = true;
                            }
                        }
                        if (!bResult)
                        {
                            MessageBox.Show("字段'" + strFields[i] + "'在表格中不存在，请联系管理员增加相应字段！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            return false;
                        }
                    }
                }
                return true;
            }
            else
            {
                return true;
            }
        }

        private string GetString(object tmpobj)
        {
            try
            {
                return tmpobj.ToString();
            }
            catch
            {
                return string.Empty;
            }
        }

        private void btnPreview_Click(object sender, EventArgs e)
        {
            reportpreviewFrm newreportpreviewFrm = new reportpreviewFrm(ds, GetReportFileName());
            newreportpreviewFrm.ShowDialog();
        }

        private string GetReportFileName()
        {
            return Application.StartupPath + "\\template\\产品资料_" + cmbDocType.Text+".rpt";
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            ReportDocument Rdoc = new ReportDocument();
            try
            {
                Rdoc.Load(GetReportFileName());
                Rdoc.SetDataSource(ds);
                Rdoc.PrintToPrinter(Convert .ToInt32( numericUpDown1 .Value) , false, 0, 0);
                if (cmbDocType.SelectedIndex == 0)
                {
                    Properties.Settings.Default.DPA报告编号 = dgv1.Rows[dgv1.Rows.Count - 1].Cells["DPA报告编号"].Value.ToString();
                    Properties.Settings.Default.Save();
                    SqlTools sqt = new SqlTools(GeneralTools.GetConnectionString(提交管理平台V1.Properties.Settings.Default.Host, "DefualtDataBase"));
                    try
                    {
                        for (int i = 0; i < ds.Tables["ReportData"].Rows.Count; i++)
                        {
                            sqt.DoCmdExecuteNonQuery(strInsertDPAID.Replace("@型号规格", GetString(ds.Tables["ReportData"].Rows[i]["型号规格"]))
                                                                                            .Replace("@批号", GetString(ds.Tables["ReportData"].Rows[i]["生产批号"]))
                                                                                            .Replace("@DPA报告编号", GetString(ds.Tables["ReportData"].Rows[i]["DPA报告编号"])));
                        }
                    }
                    catch
                    {}
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void qJToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ChangeClass("QJ");
            dgv1.AutoResizeColumns();
        }

        private void ChangeClass(string strClass)
        {
            for (int i = 0; i < dgv1.SelectedRows.Count ; i++)
            {
                dgv1.SelectedRows[i].Cells["型号规格"].Value = "(" + strClass + ") " + GetString(dgv1.SelectedRows[i].Cells["型号规格"].Value);
            }
        }

        private void jKToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ChangeClass("J/K");
            dgv1.AutoResizeColumns();
        }

        private void cToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ChangeClass("C");
            dgv1.AutoResizeColumns();
        }

        private void btnHistory_Click(object sender, EventArgs e)
        {
            frmDPAIDViewer newFrmDPAIDViewer = new frmDPAIDViewer();
            newFrmDPAIDViewer.Show();
        }
    }
}